import ElementUI from 'element-ui'
import i18n from '@/lang'

function initWebSocket(e) {
  if (typeof WebSocket === 'undefined') {
    console.log(i18n.t('msg.WEBSOCKET_NOT_SUPPORT'))
    return
  }
  const protocol = 'ws'
  var wsUri = protocol + '://127.0.0.1:8000' + process.env.VUE_APP_BASE_API + '/background/' + e
  this.socket = new WebSocket(wsUri)
  this.socket.onerror = webSocketOnError
  this.socket.onmessage = webSocketOnMessage
  this.socket.onclose = closeWebsocket
  this.socket.onopen = openSocket
}
function webSocketOnError(e) {
  ElementUI.Notification({
    title: '',
    message: 'WebSocket连接发生错误' + e,
    type: 'error',
    duration: 0
  })
}
function webSocketOnMessage(e) {
  const data = JSON.parse(e.data)
  if (data.msgType === 'INFO') {
    ElementUI.Notification({
      title: '',
      message: data.msg,
      type: 'success',
      duration: 3000
    })
  } else if (data.msgType === 'ERROR') {
    ElementUI.Notification({
      title: '',
      message: data.msg,
      type: 'error',
      duration: 1000
    })
  }
  return data
}
// 关闭websiocket
function closeWebsocket() {
  console.log('连接已关闭...')
}
function close() {
  this.socket.close() // 关闭 websocket
  this.socket.onclose = function(e) {
    console.log(e)
    console.log('关闭')
  }
}
function webSocketSend(agentData) {
  var msg = JSON.stringify(agentData)
  if (this.socket !== undefined && this.socket.readyState === 1) {
    this.socket.send(msg)
  }
}
function openSocket() {
  console.log('开启')
}
export default { initWebSocket, webSocketSend, webSocketOnMessage, close }

